package com.sctvcloud.zhaohua_sd.utils;

import android.content.Context;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.utils.OtherUtils;
import com.sctvcloud.zhaohua_sd.base.BaseActivity;
import com.sctvcloud.zhaohua_sd.base.BaseFragment;
import com.sctvcloud.zhaohua_sd.beans.FUsers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ref.WeakReference;

/**
 * Created by Administrator on 2017/2/20.
 */

public class UserManager {
    private static final String FILE_NAME = "user.o";

    private static UserManager instance;

    private static int expiredACCode;
    private static int expiredFGCode;

    private static String AcName;
    private static String FgName;

    /**
     * 用户类
     */
    private FUsers user;
    /**
     * 是否登录失效
     */
    private boolean isLoginExpired;

    private static WeakReference<BaseActivity> activeAC;
    private static WeakReference<BaseFragment> activeFragment;

    private UserManager() {

    }

    public synchronized static void setActiveAC(BaseActivity activeAC) {
        UserManager.activeAC = new WeakReference<BaseActivity>(activeAC);
    }

    public synchronized static void setActiveFragment(BaseFragment activeFragment) {
        UserManager.activeFragment = new WeakReference<BaseFragment>(activeFragment);
    }

    public static void onUserExpired() {
        if (activeFragment != null) {
            BaseFragment bf = activeFragment.get();
            if (bf != null && bf.isThisShowing()) {
                String bfN = bf.getClass().getName();
                if (FgName == null || !FgName.equals(bfN)) {
                    FgName = bfN;
                    expiredFGCode++;
                }
                bf.onUserExpired(expiredFGCode);
            }
        }
        if (activeAC != null) {
            BaseActivity ba = activeAC.get();
            if (ba != null && ba.isThisShowing()) {
                String acN = ba.getClass().getName();
                if (AcName == null || AcName.equals(acN)) {
                    AcName = acN;
                    expiredACCode++;
                }
                ba.onUserExpired(expiredACCode);
            }
        }
    }

    public static UserManager getInstance() {
        if (instance == null) {
            instance = new UserManager();
        }
        return instance;
    }

    public static boolean isLoginS(){
        return getInstance().isLogin();
    }

    public FUsers getUser() {
        return user;
    }

    public static void init(final Context context) {
        getInstance();
        new ResultAsyncTask<Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                FileInputStream inStream = null;
                ObjectInputStream ois = null;
                try {
                    inStream = context.openFileInput(FILE_NAME);
                    ois = new ObjectInputStream(inStream);
                    Object obj = ois.readObject();
                    JLog.e("read user::" + obj);
                    if (obj instanceof FUsers) {
                        instance.user = (FUsers) obj;
                    } else {
                        JLog.e("read user the obj is not user instance");
                    }

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    OtherUtils.close(ois, inStream);
                }
                return null;
            }
        }.ex();
    }

    public synchronized static void saveLogin(Context context) {
        if (instance != null && instance.user != null) {
            new ResultAsyncTask<Void>(context, "UserManager") {
                @Override
                protected Void doInBackground(Void... voids) {
                    Context co = (Context) obj;
                    FileOutputStream fos = null;
                    ObjectOutputStream oos = null;
                    try {
                        fos = co.openFileOutput(FILE_NAME, Context.MODE_PRIVATE);
                        oos = new ObjectOutputStream(fos);
                        oos.writeObject(instance.user);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        OtherUtils.close(oos, fos);
                    }
                    obj = null;
                    return null;
                }
            }.ex();
        }
    }

    public synchronized void delUserCache(final Context context) {
        if (context == null) {
            return;
        }
        new ResultAsyncTask<Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                File f = context.getFileStreamPath(FILE_NAME);
                if (f != null) {
                    JLog.e("file " + f.exists());
                    f.delete();
                }
                return null;
            }
        }.ex();
    }

    public boolean isLogin() {
        return user != null && !isLoginExpired;
    }

    public UserManager setUser(Context context, FUsers user) {
        this.user = user;
        isLoginExpired = false;
        saveLogin(context);
        return this;
    }

//    private static void readUser(Context context)

    public UserManager setLoginExpired(boolean loginExpired) {
        isLoginExpired = loginExpired;
        if(loginExpired) {
            user = null;
        }
        if (loginExpired && user != null) {
            delUserCache(activeAC != null ? activeAC.get() : null);
        }
        return this;
    }

    public String getToken() {
        if (isLogin()) {
            return user.getToken();
        }
        return null;
    }
}
